//
//  MapView.m
//  pa
//
//  Created by HaiJiao Chen on 12-7-30.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "MapView.h"
#import "GoogleMapDownloader.h"

@implementation MapView
@synthesize mapView;
@synthesize webMap;
@synthesize address;
@synthesize plat;
- (void)initlize
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageDownload:) name:GoogleMapDownloaderNotification object:nil];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initlize];
    }
    return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self initlize];
    }
    return self;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [address release];
    [plat release];
    [super dealloc];
}

- (void)setMap:(NSString*)_address withPlat:(NSString *)_plat
{
    if (![self.address isEqualToString:_address] || ![self.plat isEqualToString:_plat])
    {
        self.address = _address;
        self.plat = _plat;
        if (_address && _plat)
        {
            NSString* html = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"html" ofType:@"text"] encoding:NSUTF8StringEncoding error:nil];
            NSString* addr = [self.address stringByReplacingOccurrencesOfString:@"'" withString:@"\'"];
            NSString* pl = [self.plat stringByReplacingOccurrencesOfString:@"'" withString:@"\'"];
            html = [html stringByReplacingOccurrencesOfString:@"目的地" withString:addr];
            html = [html stringByReplacingOccurrencesOfString:@"出发地" withString:pl];
            [webMap stopLoading];
            [webMap loadHTMLString:html baseURL:nil];
            mapView.image = [[GoogleMapDownloader sharedInstance] downloadMap:_address];
        }
    }
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString* url = [[request URL] absoluteString];
    if ([url hasPrefix:@"alert://"])
    {
        NSString* temp = [url substringFromIndex:8];
        temp = [temp stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:temp delegate:nil cancelButtonTitle:@"ok" otherButtonTitles: nil];
        [alert show];
        [alert release];
        webMap.hidden = YES;
        mapView.hidden = NO;
        return NO;
    }
    return YES;
}


- (void)imageDownload:(NSNotification*)notification
{
    
    if ([self.address isEqual:[notification object]])
    {
        mapView.image = [[GoogleMapDownloader sharedInstance] downloadMap:address];
    }
}

@end
